package cn.itcast.nsfw.user.action;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;

import cn.itcast.core.action.BaseAction;
import cn.itcast.core.util.QueryHelper;
import cn.itcast.nsfw.role.service.RoleService;
import cn.itcast.nsfw.user.entity.User;
import cn.itcast.nsfw.user.entity.UserRole;
import cn.itcast.nsfw.user.service.UserService;

import com.opensymphony.xwork2.ActionContext;

public class UserAction extends BaseAction {
	
	@Resource
	private UserService userService;
	@Resource
	private RoleService roleService;
	
	private List<User> userList;
	private User user;
	
	private File headImg;
	private String headImgContentType;
	private String headImgFileName;
	private File userExcel;
	private String userExcelContentType;
	private String userExcelFileName;
	
	private String[] userRoleIds;
	private String strName;
	
	// 列表
	public String listUI() throws Exception{
		try {
			QueryHelper queryHelper = new QueryHelper(User.class, "u");
			if(user != null){
				if(StringUtils.isNotBlank(user.getName())){
					user.setName(URLDecoder.decode(user.getName(), "utf-8"));
					queryHelper.addCondition("u.name like ?", "%" + user.getName() + "%");
				}
			}
			
			pageResult = userService.getPageResult(queryHelper, getPageNo(), getPageSize());
		} catch (Exception e) {
			throw new Exception(e);
		}
		return "listUI";
	}
	// 跳转到新增页面
	public String addUI(){
		//加载角色列表
		ActionContext.getContext().getContextMap().put("roleList", roleService.findObjects());
		strName = user.getName();
		return "addUI";
	}
	// 保存新增
	public String add(){
		try {
			if(user != null){
				//处理用户头像
				if(headImg != null){//获取头像文件
					//获取到保存头像的服务器路径
					String filePath = ServletActionContext.getServletContext().getRealPath("/upload/user");
					String fileName = UUID.randomUUID().toString().replaceAll("-", "") + headImgFileName.substring(headImgFileName.lastIndexOf("."));
					//保存
					FileUtils.copyFile(headImg, new File(filePath, fileName));
					//设置用户头像路径
					user.setHeadImg("user/" + fileName);
				}
				userService.saveUserAndRole(user, userRoleIds);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "list";
	}
	// 跳转到编辑页面
	public String editUI(){
		//加载角色列表
		ActionContext.getContext().getContextMap().put("roleList", roleService.findObjects());
		if(user != null && StringUtils.isNotBlank(user.getId())){
			strName = user.getName();
			user = userService.findObjectById(user.getId());
			//处理用户角色回显
			List<UserRole> list = userService.getUserRolesByUserId(user.getId());
			if(list != null && list.size() > 0){
				userRoleIds = new String[list.size()];
				for(int i = 0; i < list.size(); i++){
					userRoleIds[i] = list.get(i).getId().getRole().getRoleId();
				}
			}
		}
		return "editUI";
	}
	// 保存编辑
	public String edit(){
		try {
			if(user != null){
				//处理用户头像
				if(headImg != null){//获取头像文件
					//获取到保存头像的服务器路径
					String filePath = ServletActionContext.getServletContext().getRealPath("/upload/user");
					String fileName = UUID.randomUUID().toString().replaceAll("-", "") + headImgFileName.substring(headImgFileName.lastIndexOf("."));
					//保存
					FileUtils.copyFile(headImg, new File(filePath, fileName));
					//设置用户头像路径
					user.setHeadImg("user/" + fileName);
				}
				userService.updateUserAndRole(user, userRoleIds);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "list";
	}
	// 删除
	public String delete(){
		strName = user.getName();
		if(user != null && StringUtils.isNotBlank(user.getId())){
			userService.delete(user.getId());
		}
		return "list";
	}
	// 批量删除
	public String deleteSelected(){
		strName = user.getName();
		if(selectedRow != null ){
			for(String id: selectedRow){
				userService.delete(id);
			}
		}
		return "list";
	}
	
	//导出用户列表
	public void exportExcel(){
		try {
			//① 获取用户列表
			userList = userService.findObjects();
			//② 导出（创建excel并且将excel输出到浏览器）
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("application/x-excel");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String("用户列表.xls".getBytes(), "ISO-8859-1"));
			ServletOutputStream outputStream = response.getOutputStream();
			userService.exportExcel(userList, outputStream);
			if(outputStream != null){
				outputStream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//导入用户列表
	public String importExcel(){
		if(userExcel != null){//1、获取Excel文档
			if(userExcelFileName.matches("^.+\\.(?i)((xls)|(xlsx))$")){
				//2、解析并插入数据库
				userService.importExcel(userExcel, userExcelFileName);
			}
			
		}
		return "list";
	}
	
	//校验用户帐号
	public void verifyAccount(){
		try {
			if(user != null){
				String res = "true";
				if(StringUtils.isNotBlank(user.getAccount())){//1、获取帐号和ID
					//2、根据帐号和ID到数据库中查询用户列表
					List<User> list = userService.findUsersByAccountAndId(user.getAccount(), user.getId());
					if(list != null && list.size() > 0){
						//说明该帐号已经存在，不用再使用
						res = "false";
					}
				}
				//3、输出校验结果
				HttpServletResponse response = ServletActionContext.getResponse();
				response.setContentType("text/html");
				ServletOutputStream outputStream = response.getOutputStream();
				outputStream.write(res.getBytes());
				outputStream.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public List<User> getUserList() {
		return userList;
	}
	public void setUserList(List<User> userList) {
		this.userList = userList;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	
	public File getHeadImg() {
		return headImg;
	}
	public void setHeadImg(File headImg) {
		this.headImg = headImg;
	}
	public String getHeadImgContentType() {
		return headImgContentType;
	}
	public void setHeadImgContentType(String headImgContentType) {
		this.headImgContentType = headImgContentType;
	}
	public String getHeadImgFileName() {
		return headImgFileName;
	}
	public void setHeadImgFileName(String headImgFileName) {
		this.headImgFileName = headImgFileName;
	}
	public File getUserExcel() {
		return userExcel;
	}
	public void setUserExcel(File userExcel) {
		this.userExcel = userExcel;
	}
	public String getUserExcelContentType() {
		return userExcelContentType;
	}
	public void setUserExcelContentType(String userExcelContentType) {
		this.userExcelContentType = userExcelContentType;
	}
	public String getUserExcelFileName() {
		return userExcelFileName;
	}
	public void setUserExcelFileName(String userExcelFileName) {
		this.userExcelFileName = userExcelFileName;
	}
	public String[] getUserRoleIds() {
		return userRoleIds;
	}
	public void setUserRoleIds(String[] userRoleIds) {
		this.userRoleIds = userRoleIds;
	}
	public String getStrName() {
		return strName;
	}
	public void setStrName(String strName) {
		this.strName = strName;
	}

}

